#!/bin/bash

# add port forward rule for libvirt vm

set -e
set -o pipefail

op=$1
vm=$2
hostport=$3
guestport=$4

usage () {
	prg=$(basename $0)
	echo ""
	echo "Usage:"
        echo "    $prg add vmname hostport guestport"
        echo "    $prg del vmname hostport guestport"
        echo "    $prg list"
	exit 1
}

update_pf()
{
    local action="-I"
    local guestip=$(virsh domifaddr "$vm" | awk '/ipv4/{print $4}' | sed 's/\/.*//')
    [ -z $guestip  ] && echo "Error: no guest ip" && usage
    [ -z $hostport  ] && echo "Error: no host port" && usage
    [ -z $guestport  ] && echo "Error: no guest port" && usage
    [ $op = "del" ] && action="-D"

    sudo iptables -t nat $action PREROUTING -p tcp --dport "$hostport" \
                -j DNAT --to "$guestip:$guestport" -m comment --comment "tag_dnat_$vm"
    sudo iptables $action FORWARD -d "$guestip/32" -p tcp -m state \
                --state NEW -m tcp --dport "$guestport" -j ACCEPT -m comment --comment "tag_new_$vm"
}

list_pf()
{
    sudo iptables-save | grep PREROUTING | grep tag |  \
        sed -r 's/.*dport ([0-9]{1,}).*tag_(.*) -j.*destination (.*)/\2\t\tlocalhost:\1 ==> \3/'
}

case $op in
	add|del) update_pf ;;
	list) list_pf ;;
	*) usage ;;
esac
